package com.sms.jiujia.utils;

import com.alibaba.fastjson2.JSON;
import com.sms.jiujia.model.MainData;
import com.sms.jiujia.model.Place;
import com.sms.jiujia.ui.setting.Constant;
import okhttp3.*;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author songmingsong
 * @date 2023/5/6
 */
public class PushMsgUtils {
    /**
     * 存放前一次推送的数据
     */
    private static String lastPushDataUrl = "";

    /**
     * pushDeer 消息推送
     *
     * @param mainData 消息体
     * @param isTest   是否测试
     */
    public static Response pushDeer(MainData mainData, Boolean isTest) throws ParseException {
        List<Place> placeList = mainData.getData().getWebsite().getPlace();
        List<Place> placeOnsite = mainData.getData().getOnsitedate().getPlace();
        placeList.addAll(placeOnsite);
        StringBuilder msgData = new StringBuilder();
        for (Place place : placeList) {
            if (!isTest && !compareTimeToNow(place.getYy_time())) {
                continue;
            }
            String msgTemplate = Constant.MSG_TEMPLATE;
            String msg = msgTemplate.replace("{yyHospital}", place.getName())
                    .replace("{yyTime}", place.getYy_time())
                    .replace("{yyAddr}", place.getAddr())
                    .replace("{yyNumber}", place.getMinge())
                    .replace("{yyMethod}", place.getMethod())
                    .replace("{yyType}", place.getPlatform());
            msgData.insert(0, msg);
        }
        String pushDeerUrl = Constant.PUSH_DEER_URL;
        String pushDataUrl = pushDeerUrl.replace("{key}", Constant.PUSH_DEER_KEY).replace("{city}", mainData.getData().getXiaoxi().get(0).getCityname()).replace("{msg}", msgData.toString());
        if (pushDataUrl.equals(lastPushDataUrl)) {
            return null;
        }
        if (!isTest) {
            lastPushDataUrl = pushDataUrl;
        }
        return push_message(pushDataUrl);
    }

    /**
     * 比较预约时间
     *
     * @param placeTime
     * @return true 可以推送
     * @throws ParseException
     */
    private static Boolean compareTimeToNow(String placeTime) throws ParseException {
        return DateUtils.changeDate(placeTime).after(new Date());
    }

    /**
     * pushDeer 消息推送请求
     *
     * @param pushDataUrl
     */
    private static Response push_message(String pushDataUrl) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        Request request = new Request.Builder()
                .url(pushDataUrl)
                .method("POST", RequestBody.create(mediaType, ""))
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }


    /**
     * 发送get请求
     *
     * @param httpurl
     * @return
     */
    private static String sendGet(String httpurl) {
        LogUtils.getLayoutConsoleLogInstance().log("[info]->" + "开始推送-->：" + httpurl);
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        // 返回结果字符串
        String result = null;
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            LogUtils.getLayoutConsoleLogInstance().log("[error]->" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.getLayoutConsoleLogInstance().log("[error]->" + e.getMessage());
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }
        LogUtils.getLayoutConsoleLogInstance().log("[info]->" + "推送结果-->：" + result);
        return result;
    }

    /**
     * 发送post请求
     *
     * @param URL
     * @param map
     * @return
     */
    private static String sendPost(String URL, Map<String, Object> map) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        HttpURLConnection conn = null;
        try {
            URL url = new URL(URL);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            //发送POST请求必须设置为true
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置连接超时时间和读取超时时间
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(10000);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept", "application/json");
            //获取输出流
            out = new OutputStreamWriter(conn.getOutputStream());
            //	            String jsonStr = "{\"qry_by\":\"name\", \"name\":\"Tim\"}";
            String jsonStr = JSON.toJSONString(map);

            out.write(jsonStr);
            out.flush();
            out.close();
            //取得输入流，并使用Reader读取
            if (200 == conn.getResponseCode()) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result.append(line);
                }
            } else {
                LogUtils.getLayoutConsoleLogInstance().log("[error]->" + +conn.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
        return result.toString();
    }
}
